package cn.edu.zut.hhr.controller;


import cn.edu.zut.hhr.entity.Commodity;
import cn.edu.zut.hhr.entity.CommodityInfo;
import cn.edu.zut.hhr.exceptions.CheckException;
import cn.edu.zut.hhr.mapper.CommodityInfoMapper;
import cn.edu.zut.hhr.service.ICommodityService;
import cn.edu.zut.hhr.utils.CheckUtil;
import cn.edu.zut.hhr.utils.ElasticSearchUtil;
import cn.edu.zut.hhr.utils.RestResponse;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.ibatis.session.SqlSession;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author hhr
 * @since 2021-06-19
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Resource
    ICommodityService commodityService;
    @Resource(name = "batchSqlSession")
    SqlSession sqlSession;
    @Resource
    ElasticSearchUtil elasticSearchUtil;

    @GetMapping("/id/{id}")
    @HystrixCommand(fallbackMethod = "getCommodityByIdFallback", ignoreExceptions = CheckException.class)
    public RestResponse<Map<String,Object>> getCommodityById(@PathVariable("id") Long id){
        try {
            Map<String,Object> map = elasticSearchUtil.searchDataById(elasticSearchUtil.getIndex(),id.toString());
            return RestResponse.success(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RestResponse.fail("商品不存在");
    }

    public RestResponse<Map<String,Object>> getCommodityByIdFallback(@PathVariable("id") Long id){
        return RestResponse.fail("当前访问人数过多请稍后再试");
    }

    @GetMapping("/name/{name}")
//    @HystrixCommand(fallbackMethod = "getCommodityByNameFallback", ignoreExceptions = CheckException.class)
    public RestResponse<String> getCommodityByName(@PathVariable("name") String name){
        String list = null;
        try {
            list = elasticSearchUtil.searchData("cname",name,elasticSearchUtil.getIndex());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RestResponse.success("",list);
    }

    public RestResponse<String> getCommodityByNameFallback(@PathVariable("name") String name){
        return RestResponse.fail("当前访问人数过多请稍后再试");
    }

    /**
     * 员工才可以上下架商品
     * @param commodity
     * @return
     */
    @PostMapping("/")
    @PreAuthorize("hasAnyAuthority('admin','staff')")
//    @HystrixCommand(fallbackMethod = "commodityFallback", ignoreExceptions = CheckException.class)
    public RestResponse<Commodity> insertCommodity(@RequestBody Commodity commodity){
        CheckUtil.notNull(commodity.getCname(),"商品名不能为空");
        CheckUtil.notNull(commodity.getPrice(),"价格不能为空");
        if(commodity.getVipPrice() == null){
            commodity.setVipPrice(commodity.getPrice());
        }
        if(commodity.getCount() == null){
            commodity.setCount(1000);
        }
        commodityService.save(commodity);
        try {
            elasticSearchUtil.addData(JSON.toJSONString(commodity),elasticSearchUtil.getIndex(),commodity.getId().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        setCommodityInfo(commodity.getId(), "location", commodity.getLocation());
        setCommodityInfo(commodity.getId(), "type", commodity.getType());

        return RestResponse.success(commodity);
    }

    public RestResponse<Commodity> commodityFallback(Commodity commodity){
        System.out.println("commodityFallback");
        return RestResponse.fail("当前访问人数过多,请稍后重试");
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('admin','staff')")
//    @HystrixCommand(fallbackMethod = "commodityFallbackById", ignoreExceptions = CheckException.class)
    public RestResponse<Boolean> deleteCommodity(@PathVariable("id") Long id){
        try {
            elasticSearchUtil.deleteDataById(elasticSearchUtil.getIndex(),id.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return RestResponse.success(commodityService.removeById(id));
    }

    public RestResponse commodityFallbackById(Long id){
        System.out.println("commodityFallbackById");
        return RestResponse.fail("当前访问人数过多请稍后重试");
    }

    private void setCommodityInfo(Long cid, String key, List<String> list){
        CommodityInfoMapper commodityInfoMapper = sqlSession.getMapper(CommodityInfoMapper.class);
        for(String value: list){
            CommodityInfo commodityInfo = new CommodityInfo();
            commodityInfo.setCid(cid);
            commodityInfo.setKey(key);
            commodityInfo.setValue(value);
            commodityInfoMapper.insertCommodityInfo(commodityInfo);
        }
        sqlSession.commit();
    }

//    public Commodity getCommodity(Map<String, Object> map) throws IllegalAccessException {
//        Commodity commodity = new Commodity();
//        Class clazz = commodity.getClass();
//        for(Map.Entry<String, Object> entry: map.entrySet()){
//
//            Field field = null;
//            try {
//                //如果不存在该属性就什么也不做,继续给下一个属性赋值
//                field = clazz.getDeclaredField(entry.getKey());
//                //如果可以赋值,就赋值
//                if(entry.getValue().getClass().isAssignableFrom(field.getType())){
//                    field.setAccessible(true);
//                    field.set(commodity,entry.getValue());
//                }
//            } catch (NoSuchFieldException e) {
//                System.out.println(clazz.getName() + "类不存在" + entry.getKey() + "属性");
//            }
//        }
//        return commodity;
//    }

}
